<template>
  <div class="editor-page">
    <div class="container page">
      <div class="row">
        <div class="col-md-10 offset-md-1 col-xs-12">
          <form>
            <fieldset>
              <fieldset class="form-group">
                <input type="text" class="form-control form-control-lg" placeholder="Article Title" v-model.trim="article.title" required>
              </fieldset>
              <fieldset class="form-group">
                <input type="text" class="form-control"  v-model.trim="article.description" required placeholder="What's this article about?">
              </fieldset>
              <fieldset class="form-group">
                <textarea class="form-control" rows="8"  v-model.trim="article.body" required placeholder="Write your article (in markdown)"></textarea>
              </fieldset>
              <fieldset class="form-group">
                <input type="text" class="form-control" placeholder="Enter tags" v-model.trim="article.tagList"><div class="tag-list"></div>
              </fieldset>
              <button class="btn btn-lg pull-xs-right btn-primary" type="button" :submitDisabled='submitDisabled' @click="onSubmit"> {{$route.name == 'editor' ? 'Editor Article':'Publish Article'}} </button>
            </fieldset>
          </form>
        </div>

      </div>
    </div>
  </div>
</template>
<script>
import { getArticle, editorArticle, createArticle } from '@/api/article'
export default {
  middleware: 'authenticated',
  data(){
    return{
      article: {
        title: '',
        description: '',
        body: '',
        tagList: ''
      },
      submitDisabled: false // 发布按钮是否禁用
    }
  },
  async asyncData({route, params}){
    // 只有在编辑的时候才需要加载文章详情数据
    if(route.name === 'editor'){
      // 获取文章详情数据
      const { article } = await getArticle(params.slug)
      return { article }
    } else {
      return {}
    }
  },
  methods:{
    onSubmit(){
      this.submitDisabled = true
      const { title, description, body } = this.article
      const tagList = typeof(this.article.tagList) == 'string' ? this.article.tagList.split(',') : this.article.tagList
      const condition = {title, description, body, tagList}
      if(this.$route.name === 'editor'){
        //编辑文章
        editorArticle(this.$route.params.slug, condition).then(()=>{
          this.$router.push({name: 'article', params: {slug: this.$route.params.slug}})
        }).finally(()=>{
          this.submitDisabled = false
        })
      } else {
        //发布文章
        createArticle(condition).then((res)=>{
          this.$router.push({name: 'article', params: { slug: res.article.slug } })
        }).finally(()=>{
          this.submitDisabled = false
        })
      }
    }
  }
}
</script>